<?php

namespace app\admin\model\customer;

use app\admin\model\Admin;
use app\admin\model\customer\package\User;
use think\Config;
use think\Model;


class Package extends Model
{
    // 表名
    protected $name = 'customer_package';
    protected $pk = 'package_id';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'signature_time_text',
        'create_time_text',
        'service_ids',
        'service_list',
        'admin_info',
        'account_names',
        'outworker_names',
        'sales_commission',
        'account_commission',
        'outworker_commission',
        'total_data',
        'kuaiji_names',
        'waiqin_names',
    ];

    public function getKuaijiNamesAttr($value, $data)
    {
        $admin_ids = (new User())->where([
            'package_id' => $data['package_id'],
            'identity' => 0
        ])->column('admin_id');
        return (new Admin())->where('id', 'in', $admin_ids)->column('nickname');
    }

    public function getWaiqinNamesAttr($value, $data)
    {
        $admin_ids = (new User())->where([
            'package_id' => $data['package_id'],
            'identity' => 1
        ])->column('admin_id');
        return (new Admin())->where('id', 'in', $admin_ids)->column('nickname');
    }


    public function getTotalDataAttr($value, $data)
    {
        $total = [];
        $total['standard_price'] = (new Service())->where(['package_id' => $data['package_id']])->sum('standard_price');
        $total['deal_price'] = (new Service())->where(['package_id' => $data['package_id']])->sum('deal_price');
        $total['cost_price'] = (new Service())->where(['package_id' => $data['package_id']])->sum('cost_price');
        $total['collection_price'] = (new Service())->where(['package_id' => $data['package_id']])->sum('collection_price');
        $total['balance_price'] = (new Service())->where(['package_id' => $data['package_id']])->sum('balance_price');
        return $total;
    }

    public function getSalesCommissionAttr($value, $data)
    {
        return (new Service())->where(['package_id' => $data['package_id']])->sum('sales_commission');
    }

    public function getAccountCommissionAttr($value, $data)
    {
        return (new Service())->where(['package_id' => $data['package_id']])->sum('account_commission');
    }

    public function getOutworkerCommissionAttr($value, $data)
    {
        return (new Service())->where(['package_id' => $data['package_id']])->sum('outworker_commission');
    }


    public function getAdminInfoAttr($value, $data)
    {
        return Admin::get($data['admin_id']);
    }

    public function getSignatureTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['signature_time']) ? $data['signature_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getAccountNamesAttr($value, $data)
    {
        $names = (new Admin())->where('id', 'in', $data['account_ids'])->column('nickname');
        return $names ? implode(',', $names) : '';
    }

    public function getOutworkerNamesAttr($value, $data)
    {
        $names = (new Admin())->where('id', 'in', $data['outworker_ids'])->column('nickname');
        return $names ? implode(',', $names) : '';
    }


    public function getServiceListAttr($value, $data)
    {
        return (new Service())->where(['package_id' => $data['package_id']])->select();
    }

    public function getServiceIdsAttr($value, $data)
    {
        return (new Service())->where(['package_id' => $data['package_id']])->column('service_id');
    }

    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['create_time']) ? $data['create_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setSignatureTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setCreateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    public function customer()
    {
        return $this->hasOne('Intention', 'id', 'customer_id');
    }


    public function generateContract($package_id = '')
    {
        $package_id = $package_id ? $package_id : $this->package_id;

        //套餐信息
        $package = $this
            ->with(['customer'])
            ->where(['package_id' => $package_id])->find();
        if (!$package || !$package->customer) {
            return false;

        }


        $template_name = $package->customer->customer_identity == 0 ? 'gr' : 'gr';
        $templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('template/' . $template_name . '.docx');


        // 生成表格
        $where = [
            'package_id' => $package_id,
        ];
        $service_list = (new \app\admin\model\customer\Service)->where($where)->select();
        $templateProcessor->cloneRow('service_name', count($service_list));

        foreach ($service_list as $k => $item) {
            $id = $k + 1;
            $templateProcessor->setValue("service_name#{$id}", $item->service_name);
            $templateProcessor->setValue("service_price#{$id}", $item->deal_price);
            $templateProcessor->setValue("service_time#{$id}", $item->month ? $item->month . '个月' : "一次性服务");
        }

        $standard_price = (new \app\admin\model\customer\Service)->where($where)->sum('deal_price');
        $ledger_expenses = (new \app\admin\model\customer\Service)->where($where)->sum('ledger_expenses');


        $admin_info = Admin::get($package->admin_id);
        if ($package->customer->customer_identity == 0) {
            $templateProcessor->setValue('full_name', $package->customer->full_name);
            $templateProcessor->setValue('idnumber', $package->customer->idnumber);
            $templateProcessor->setValue('signatory', $package->customer->full_name);
        } else {
            $templateProcessor->setValue('full_name', $package->customer->corporate_name);
            $templateProcessor->setValue('idnumber', null);
            $templateProcessor->setValue('signatory', $package->customer->signatory);

//            $templateProcessor->setValue('corporate_name', $package->customer->corporate_name);
        }


        $templateProcessor->setValue('mobile', $package->customer->mobile);
        $templateProcessor->setValue('admin_name', $admin_info->nickname);
        $templateProcessor->setValue('admin_mobile', $admin_info->mobile);
        $templateProcessor->setValue('service_desc', $package->service_desc);
        $templateProcessor->setValue('standard_price', $standard_price);
        $templateProcessor->setValue('total_price', $standard_price);
        $templateProcessor->setValue('ledger_expenses', $ledger_expenses ? $ledger_expenses : '/');
        $templateProcessor->setValue('pay_type1', $package->pay_type == 1 ? '☑' : '☐');
        $templateProcessor->setValue('pay_type2', $package->pay_type == 2 ? '☑' : '☐');

        $templateProcessor->setImageValue('signature1', [
            'path' => 'template/empty.png',
            'width' => 100,
            'height' => 40,
            'ratio' => true
        ]);

        if ($package->signature_url) {
            $templateProcessor->setImageValue('signature', [
                'path' => str_replace('/uploads', 'uploads', $package->signature_url),
                'width' => 100,
                'height' => 40,
                'ratio' => true
            ]);

            if ($package->signature_time) {
                $templateProcessor->setValue('signing_year_time', date("Y", $package->signature_time));
                $templateProcessor->setValue('signing_month_time', date("m", $package->signature_time));
                $templateProcessor->setValue('signing_day_time', date("d", $package->signature_time));
            } else {
                $templateProcessor->setValue('signing_year_time', '    ');
                $templateProcessor->setValue('signing_month_time', '    ');
                $templateProcessor->setValue('signing_day_time', '    ');
            }


        } else {
            $templateProcessor->setImageValue('signature', [
                'path' => 'template/empty.png',
                'width' => 100,
                'height' => 40,
                'ratio' => true
            ]);
            if ($package->audit_time) {
                $templateProcessor->setValue('signing_year_time', date("Y", $package->audit_time));
                $templateProcessor->setValue('signing_month_time', date("m", $package->audit_time));
                $templateProcessor->setValue('signing_day_time', date("d", $package->audit_time));
            } else {
                $templateProcessor->setValue('signing_year_time', '    ');
                $templateProcessor->setValue('signing_month_time', '    ');
                $templateProcessor->setValue('signing_day_time', '    ');
            }
        }

        // 公司盖章
//
//        $official_seal = Config::get('site.official_seal');
//        if($official_seal){
//            $official_seal=str_replace('/u','u',$official_seal);
//            $templateProcessor->setImageValue('yfgz', [
//                'path' => $official_seal,
//                'width' => 200,
//                'height' => 140,
//                'ratio' => true
//            ]);
//        }else{
//            $templateProcessor->setImageValue('yfgz', [
//                'path' => 'template/empty.png',
//                'width' => 100,
//                'height' => 40,
//                'ratio' => true
//            ]);
//        }


        $contract_url = 'contract/contract_' . $package->package_id . '_' . uniqid() . '_' . time() . '.docx';
        $package->save(['contract_url' => $contract_url]);
        $templateProcessor->saveAs($contract_url);
    }

}
